<?php
App::uses('AppController', 'Controller');
/**
 * Fotos Controller
 *
 * @property Foto $Foto
 */
class FotosController extends AppController {
	
	var $components = array('Upload', 'FotosService');

	function beforeFilter(){
		parent::beforeFilter();
		$this->Auth->allow('index');
		$this->Upload->type = array('text/plain');
		$this->Upload->size = 3166230;
	}

	public function index($idFotos){
		$this->layout = null;
		$this->set('fotos', $this->Foto->find('first', array('conditions'=>array('id_fotos'=>$idFotos))));
	}
	
	public function edit($id = null) {
		$this->layout = null;
		$this->Foto->id = $id;
		if (!$this->Foto->exists()) {
			throw new NotFoundException(__('Invalid foto'));
		}
		if(!$this->Foto->Anuncio->anuncioPertenceAoUsuario($this->Foto->Anuncio->read('usuario_id' ,$id), $this->usuarioAtual['id_usuarios']))
			throw new MethodNotAllowedException();
		// AÇÃO SALVAR
		if ($this->request->is('post') || $this->request->is('put')) {
			foreach($this->data['Foto'] as $key=>$item){
				if($key !== "id_fotos")
					$fotos[] = $item;
			}
			if($this->Upload->validar($fotos, true)){
				$pasta = 'fotos'.DS.$this->usuarioAtual['cpf'].DS.'anuncio'.$id;
				if($this->Upload->armazenar($pasta, $fotos, true)){
					$this->data = $this->FotosService->adaptacaoBD($this->data, $pasta);
					$this->request->data['Foto']['thumb'] = str_replace("\\", "/",$pasta).'/thumb.png';
					if ($this->Foto->save($this->request->data)) {
						$this->Session->setFlash(__('The foto has been saved'));
					} else {
						$this->Session->setFlash(__('The foto could not be saved. Please, try again.'));
					}
				}
				else{ $this->Session->setFlash('ERRO DE ARMAZENAMENTO');}
			}
			else{ $this->Session->setFlash('ERRO DE VALIDACAO');}
			$this->redirect(array('controller'=>'anuncios', 'action'=>'meus_anuncios'));
		// AÇÃO PEDIR FORMULÁRIO
		} else {
			$this->set('anuncio', $this->Foto->Anuncio->read(null, $id));
			$this->request->data = $this->Foto->read(null, $id);
		}
	}

/**
 * delete method
 *
 * @param string $id
 * @return void
 */
	public function delete($id = null, $foto) {
		//if (!$this->request->is('post')) {
		//	throw new MethodNotAllowedException();
		//}
		$this->Foto->id = $id;
		if (!$this->Foto->exists()) {
			throw new NotFoundException(__('Invalid foto'));
		}
		$dados = $this->FotosService->delete($this->Foto->read(null, $id), $foto);
		if (is_array($dados)) {
			if($this->Foto->save($dados))
				$this->Session->setFlash(__('Foto deleted'));
			//$this->redirect(array('action'=>'delete'));
		}
		$this->Session->setFlash(__('Foto was not deleted'));
		//$this->redirect(array('action' => 'delete'));
	}
}
